package LocalDB;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class LocalDataBase {
	
	/**
	 *	本地数据库初始化变量
	 *		conn                  JDBC数据库连接
	 *		stm                   JDBC数据库statement
	 *		rs                    JDBC数据库查询结果
	 *		obj                   反射类对象容器
	 */
	private static Connection conn;
	private static Statement stm;
	private static ResultSet rs;
	private static Class<?> obj;
	
	private final static Logger logger = LogManager.getLogger(LocalDataBase.class.getName());
	
	/**
	 *	初始化对本地数据库的conn，获取全局变量对象
	 *
	 *	@error ClassNotFoundException
	 *		数据库驱动缺失
	 *
	 *	@error SQLException
	 *		数据库连接出错
	 *
	 *	@create 2014.10.17
	 *	@latest 2014.10.17
	 *
	 *	@author sundaydx
	 *	@since 2.0.1
	 *	@version 2.0.1
	 */
	static {
		
		/** 创建数据库的连接 */
		try {
			Class.forName("org.sqlite.JDBC");
			conn = DriverManager.getConnection("jdbc:sqlite:Config.db");
			stm = conn.createStatement();
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			logger.warn("数据库驱动加载失败" + e.getMessage());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			logger.warn("本地数据库连接创建失败" + e.getMessage());
		}
		
	}
	
	/**
	 *	设置全局变量值
	 *	<p>
	 *	自动修改现行全局变量，默认只支持int、String两种类型变量
	 *
	 *	@param keyName
	 *		全局变量名
	 *
	 *	@param keyValue
	 *		全局变量值
	 *
	 *	@throws SecurityException
	 *		越界访问（小概率）
	 *
	 *	@throws NoSuchFieldException
	 *		变量不存在
	 *
	 *	@throws IllegalAccessException
	 *		变量非法设置（针对私有变量）
	 *
	 *	@throws IllegalArgumentException
	 *		变量设值类型错误
	 *
	 *	@create 2014.10.18
	 *	@latest 2014.10.18
	 *
	 *	@author sundaydx
	 *	@since 2.0.1
	 *	@version 2.0.1 
	 */
	private static void changeConfig(String keyName, String keyValue) throws 
		NoSuchFieldException, SecurityException, IllegalArgumentException, 
		IllegalAccessException {
		
		/** 通过变量名获取对应变量 */
		Field key = obj.getDeclaredField(keyName);
		
		/** 判断类型，进行赋值 */
		if(key.getType().getName().equalsIgnoreCase("int")) {
			key.set(obj, Integer.valueOf(keyValue));
		} else {
			key.set(obj, keyValue);
		}
		
		logger.info("变更全局变量值 " + keyName + ":" + keyValue);
		
	}
	
	private static ResultSet getQuery(String sql) throws SQLException {
		
		return stm.executeQuery(sql);
	}

	public static void getConfig(String Mac) throws SQLException {
		String getConfigSQL = "select * from " + Mac;
		
		rs = getQuery(getConfigSQL);
	}

}
